package com.emm.yixun.website.controller.marketing;

//框架包
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.common.model.Customer;
import com.emm.yixun.common.model.HaveReceiveRefund;
import com.emm.yixun.common.model.HaveReceiveRefundInfo;
import com.emm.yixun.common.model.MortgageRecord;
import com.emm.yixun.common.model.NeedReceiveRefund;
import com.emm.yixun.common.model.NeedReceiveRefundInfo;
import com.emm.yixun.common.model.PayDeposit;
import com.emm.yixun.common.model.ProjectRoom;
import com.emm.yixun.common.model.ReserveArea;
import com.emm.yixun.common.model.Role;
import com.emm.yixun.common.model.Signed;
import com.emm.yixun.common.model.SignedInfo;
import com.emm.yixun.common.model.SubscribeInfo;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.CustomerDto;
import com.emm.yixun.common.model.dto.HaveReceiveRefundDto;
import com.emm.yixun.common.model.dto.HaveReceiveRefundInfoDto;
import com.emm.yixun.common.model.dto.MortgageRecordDto;
import com.emm.yixun.common.model.dto.NeedReceiveRefundDto;
import com.emm.yixun.common.model.dto.NeedReceiveRefundInfoDto;
import com.emm.yixun.common.model.dto.ProjectRoomDto;
import com.emm.yixun.common.model.dto.RoleDto;
import com.emm.yixun.common.model.dto.UserDto;
import com.emm.yixun.common.model.enums.BusinessFlagEnum;
import com.emm.yixun.common.model.enums.BusinessTypeEnum;
import com.emm.yixun.common.model.enums.DocTypeEnum;
import com.emm.yixun.common.model.enums.HousingFundTypeEnum;
import com.emm.yixun.common.model.enums.PaymentMethodEnum;
import com.emm.yixun.common.model.enums.StatementTypeEnum;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.page.PageUtil;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.customer.service.CustomerServiceFacade;
import com.emm.yixun.customer.service.PayDepositServiceFacade;
import com.emm.yixun.customer.service.SignedServiceFacade;
import com.emm.yixun.customer.service.SubscribeServiceFacade;
import com.emm.yixun.estate.service.ProjectRoomServiceFacade;
import com.emm.yixun.marketing.service.HaveReceiveRefundServiceFacade;
import com.emm.yixun.marketing.service.MortgageRecordServiceFacade;
import com.emm.yixun.marketing.service.NeedReceiveRefundServiceFacade;
import com.emm.yixun.marketing.service.ReserveAreaServiceFacade;
import com.emm.yixun.system.service.MerchantServiceFacade;
import com.emm.yixun.system.service.RoleServiceFacade;
import com.emm.yixun.system.service.UserServiceFacade;
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.common.utils.base.Const;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.controller.base.BaseController;
import com.emm.yixun.website.service.marketing.HaveReceiveRefundService;
//common
//website
//变化的引用
import com.emm.yixun.website.service.marketing.NeedReceicerefundExportService;
import com.emm.yixun.website.utils.ExcelUtil;

@Controller
@RequestMapping("/marketing/haveReceiveRefund/")
public class HaveReceiveRefundController extends BaseController<HaveReceiveRefund> {

	@Autowired
	private HaveReceiveRefundServiceFacade haveReceiveRefundServiceFacade;
	@Autowired
	private NeedReceiveRefundServiceFacade needReceiveRefundServiceFacade;
	@Autowired
	private SignedServiceFacade signedServiceFacade;
	@Autowired
	private ReserveAreaServiceFacade reserveAreaServiceFacade;
	@Autowired
	private PayDepositServiceFacade payDepositServiceFacade;
	@Autowired
	private SubscribeServiceFacade subscribeServiceFacade;
	@Autowired
	private UserServiceFacade userServiceFacade;
	@Autowired
	private CustomerServiceFacade customerServiceFacade;
	@Autowired
	private HaveReceiveRefundService haveReceiveRefundService;
	@Autowired
	private ProjectRoomServiceFacade projectRoomServiceFacade;
	@Autowired
	private MerchantServiceFacade merchantServiceFacade;
	@Autowired
	private MortgageRecordServiceFacade mortgageRecordServiceFacade;
	@Autowired
	private RoleServiceFacade roleServiceFacade;
	@Autowired
	private NeedReceicerefundExportService needReceicerefundExportService;

	@RequestMapping(value = "index")
	public String index(ModelMap map) {
		if (doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "fin:needReceive:checkList")) {
			User user = ShiroUtil.getCurrentUser();
			// 认筹开关,默认未关闭(false) ,true已关闭
			boolean payDepositOff = false;
			Response<Boolean> response = merchantServiceFacade.merPayDepositOff(user.getMerchantId());
			if (response.isSuccess()) {
				payDepositOff = response.getEntity();
			}
			// 查询菜单按钮权限
			map.put("permitBtn", getPermissionBtnArray());
			map.put("payDepositOff", payDepositOff);
			return "/marketing/haveReceiveRefund/list";
		}
		return Const.NO_AUTHORIZED_URL;
	}

	// 新增返回实体对象
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes add(HaveReceiveRefundDto dto) {
		AjaxRes ar = getAjaxRes();

		/*
		 * 1.判断权限2.调用新增接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "marketing:haveReceiveRefund:add"))) {
			try {
				User user = ShiroUtil.getCurrentUser();
				dto.setMerchantId(user.getMerchantId());
				dto.setCreateUserId(user.getId());
				dto.setDelFlag("0");
				dto.setUpdateUserId(user.getId());
				dto.setUpdateTime(new Date());
				Response<HaveReceiveRefundDto> response = haveReceiveRefundServiceFacade.save(dto);
				if (response.isSuccess()) {
					ar.setSucceedMsg(Const.SAVE_SUCCEED);
				} else {
					ar.setFailMsg(Const.SAVE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.SAVE_FAIL);
			}
		}
		return ar;
	}

	// 新增返回实体对象
	@RequestMapping(value = "addRefund")
	@ResponseBody
	public boolean addRefund(HttpServletRequest request, HaveReceiveRefundDto dto) {
		boolean flag = false;
		/*
		 * 1.判断权限2.调用新增接口3.返回信息
		 */
		if (doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "fin:haveReceive:refund")) {
			try {
				HaveReceiveRefundDto entity = new HaveReceiveRefundDto();

				String id = request.getParameter("refundId");
				if (StringUtils.isBlank(id)) {
					return flag;
				}
				// 标识是待退款提交还是已收款提交 need == 待退款 ，have == 已收款
				String needOrHave = request.getParameter("needOrHave");
				if ("have".equals(needOrHave)) {
					Response<HaveReceiveRefund> resp = haveReceiveRefundServiceFacade.findById(Long.parseLong(id));
					if (resp.getEntity() == null) {
						return flag;
					}
					BeanUtils.copyProperties(resp.getEntity(), entity);
					entity.setHaveReceiveId(resp.getEntity().getId());
					entity.setOpSource("1");
				} else if ("need".equals(needOrHave)) {
					Response<NeedReceiveRefund> resp = needReceiveRefundServiceFacade.findById(Long.parseLong(id));
					if (resp.getEntity() == null) {
						return flag;
					}
					BeanUtils.copyProperties(resp.getEntity(), entity);
					entity.setReceivablesType(resp.getEntity().getBusinessType()); // 业务类型
					entity.setRelationId(resp.getEntity().getRelationId());// 业务ID
					entity.setReceivablesId(resp.getEntity().getId()); // 应收款ID
					entity.setDeductibleAmount(new BigDecimal("0")); // 抵扣金额
					entity.setTransferStatus("0"); // 转账状态 0 正常 1 已转账
					entity.setOpSource("0");
				} else {
					return flag;
				}

				entity.setBankAccount(dto.getBankAccount()); // 银行账号
				entity.setStatementId(dto.getStatementId()); // 结算人员
				entity.setStatementType(dto.getStatementType()); // 结算类型
				entity.setRefundRemark(dto.getRefundRemark()); // 退款摘要
				entity.setDocType("1"); // 已退款
				entity.setReChecked("0"); // 未复核
				// 结算日期
				String date = request.getParameter("date");
				if (StringUtils.isNotBlank(date)) {
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					entity.setStatementDate(sdf.parse(date));
				}
				String counterFee = request.getParameter("counterFee");
				if (StringUtils.isBlank(counterFee)) {
					counterFee = "0";
				}

				boolean flag1 = haveReceiveRefundService.addRefund(entity, Long.parseLong(id), new BigDecimal(
						counterFee), dto.getRealAmount(), needOrHave);
				if (flag1) {
					return true;
				} else {
					return flag;
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
			}
		}
		return flag;
	}

	// 换票
	@RequestMapping(value = "view")
	public String view(Long id, Model model) {
		/*
		 * 1.判断权限2.调用查看接口3.返回信息
		 */
		if (doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "fin:haveReceive:forTickets")) {
			try {
				Response<HaveReceiveRefund> response = haveReceiveRefundServiceFacade.findById(id);
				if (response.isSuccess()) {
					model.addAttribute("model", response.getEntity());
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
			}
		}
		return "/marketing/haveReceiveRefund/tickets";
	}

	// 复核
	@RequestMapping(value = "re_checked_view")
	public String re_checked_view(Long id, Model model) {
		/*
		 * 1.判断权限2.调用查看接口3.返回信息
		 */
		if (doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "fin:needReceive:check")) {
			try {
				Response<HaveReceiveRefundInfo> response = haveReceiveRefundServiceFacade.findInfoById(id);
				if (response.isSuccess()) {
					HaveReceiveRefundInfo info = response.getEntity();
					if (StringUtils.isNotBlank(info.getHousingFundType())) {
						// 房款类型
						info.setRelationType(HousingFundTypeEnum.getByNo(info.getHousingFundType()).getDes());
					}
					if (StringUtils.isNotBlank(info.getBusinessFlag())) {
						// 业务标志
						info.setBusinessType(BusinessFlagEnum.getByNo(info.getBusinessFlag()).getDes());
					}
					/*
					 * if(StringUtils.isNotBlank(info.getPaymentMethod())){ //结算方式
					 * info.setPaymentMethod_name(PaymentMethodEnum.getByNo (info.getPaymentMethod()).getDes()); }
					 */
					if (StringUtils.isNotBlank(info.getNewBillCode())) {
						// 当新票据号码不为空时，取新票据号码
						info.setBillCode(info.getNewBillCode());
					}
					if (info.getStatementType() != null) {
						info.setPaymentMethod_name(StatementTypeEnum.getByNo(info.getStatementType() + "").getDes());
					}
					model.addAttribute("model", info);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
			}
		}
		return "/marketing/haveReceiveRefund/re_checked";
	}

	// 退款
	@RequestMapping(value = "refund_view")
	public String refund_view(Long id, Model model) {
		/*
		 * 1.判断权限2.调用查看接口3.返回信息
		 */
		if (doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "fin:haveReceive:refund")) {
			try {
				Response<HaveReceiveRefundInfo> response = haveReceiveRefundServiceFacade.findInfoById(id);
				if (response.isSuccess()) {
					HaveReceiveRefundInfo info = response.getEntity();
					if (info.getStatementType() != null) {
						info.setPaymentMethod_name(StatementTypeEnum.getByNo(info.getStatementType() + "").getDes());
					}
					if (info.getRelationId() != null) {
						if (info.getReceivablesType().equals(BusinessTypeEnum.DEPOSIT.getNo())) {
							// 认筹
							Response<PayDeposit> resp = payDepositServiceFacade.findById(info.getRelationId());
							if (resp.isSuccess() && resp.getEntity() != null) {
								info.setRelation("认筹");
								info.setRelationCode(resp.getEntity().getDepositCode());
								// info.setCalculatArea(resp.getEntity().getCalculateArea().toString());
								// info.setPrice(resp.getEntity().getPayDepositAmount().toString());
							}
						} else if (info.getReceivablesType().equals(BusinessTypeEnum.SUBSCRIBE.getNo())) {
							// 认购
							Response<SubscribeInfo> resp = subscribeServiceFacade.findByIdInfo(info.getRelationId());
							if (resp.isSuccess() && resp.getEntity() != null) {
								info.setRelation("认购");
								info.setRelationCode(resp.getEntity().getSubscribeCode());
								// info.setCalculatArea(resp.getEntity().getCalculateArea().toString());
								// info.setPrice(resp.getEntity().getDepositReceivable().toString());
								if (resp.getEntity() != null) {
									info.setAgent_name(resp.getEntity().getUserName());
								}
							}
						} else if (info.getReceivablesType().equals(BusinessTypeEnum.SIGNED.getNo())) {
							// 查询签约信息
							Response<SignedInfo> resp = signedServiceFacade.findByIdInfo(info.getRelationId());
							if (resp.isSuccess() && resp.getEntity() != null) {
								info.setRelation("签约");
								info.setRelationCode(resp.getEntity().getSignCode());
								info.setCalculatArea(resp.getEntity().getCalculateArea().toString());
								info.setPrice(resp.getEntity().getSignPrice());
								info.setTotalPrice(resp.getEntity().getSignAmount());
								info.setRelationDate(resp.getEntity().getDidTime());
								if (resp.getEntity() != null) {
									info.setAgent_name(resp.getEntity().getUserName());
								}
							}
						} else if (info.getBusinessType().equals(BusinessTypeEnum.AREA.getNo())) {
							// 面积补差
							Response<ReserveArea> res = reserveAreaServiceFacade.findById(info.getRelationId());
							if (res.isSuccess() && res.getEntity() != null) {
								info.setRelation("面积补差");
								info.setRelationCode(res.getEntity().getId() + "");
								// 签约信息
								Response<Signed> resp = signedServiceFacade.findById(info.getRelationId());
								if (resp.isSuccess() && resp.getEntity() != null) {
									info.setCalculatArea(resp.getEntity().getCalculateArea().toString());
									info.setPrice(resp.getEntity().getSignPrice());
									info.setTotalPrice(resp.getEntity().getSignAmount());
									info.setRelationDate(resp.getEntity().getDidTime());
									if (resp.getEntity().getAgentId() != null) {
										Response<User> resUser = userServiceFacade.findById(resp.getEntity()
												.getAgentId());
										info.setAgent_name(resUser.getEntity().getUserName());
									}
								}
							}
						}
					}
					User user = ShiroUtil.getCurrentUser();
					model.addAttribute("userId", user.getId());
					model.addAttribute("model", info);
					model.addAttribute("needOrHave", "have");
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
			}
		}
		return "/marketing/haveReceiveRefund/refund";
	}

	// 冲销和复核
	@RequestMapping(value = "edit")
	@ResponseBody
	public boolean edit(HttpServletRequest request, String checkedFlag, HaveReceiveRefundDto dto) {
		/*
		 * checkedFlag 1复核 2冲销
		 */
		if (StringUtils.isBlank(checkedFlag)) {
			checkedFlag = "2";
		}
		if (doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "fin:haveReceive:writeOff")) {
			try {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				// 更换票据号码日期
				String date = request.getParameter("date");
				if (StringUtils.isNotBlank(date)) {

					dto.setBillDate(sdf.parse(date));
				}
				// 结算日期
				String cdate = request.getParameter("cdate");
				if (StringUtils.isNotBlank(cdate)) {
					dto.setCheckDate(sdf.parse(cdate));
				}
				String result = request.getParameter("result");
				if ("1".equals(result)) {
					User user = ShiroUtil.getCurrentUser();
					dto.setCheckUserId(user.getId());
				}
				// 处理应收款记录，当应收款>已收款，则回复应收款记录继续
				Response<HaveReceiveRefund> hrResponse = haveReceiveRefundServiceFacade.findById(dto.getId());
				Response<Integer> response = haveReceiveRefundServiceFacade.updateByPrimaryKey(dto, true);
				if (response.isSuccess()) {
					if (hrResponse.isSuccess()) {
						if (checkedFlag.equals("2")) {
							String opSource = hrResponse.getEntity().getOpSource();
							if (StringUtils.isNotBlank(opSource) && opSource.equals("1")) {
								// 已收款退款,做冲销操作 ，已收金额=原已收金额+冲销金额，原记录更新为未删除
								Long haveReceiveId = hrResponse.getEntity().getHaveReceiveId();
								if (null != haveReceiveId) {
									Response<HaveReceiveRefund> hrrRespose = haveReceiveRefundServiceFacade
											.findById(haveReceiveId);
									HaveReceiveRefundDto edit = new HaveReceiveRefundDto();
									edit.setId(haveReceiveId);
									// 已收金额=原已收金额+冲销金额
									edit.setRealAmount(hrrRespose.getEntity().getRealAmount()
											.add(hrResponse.getEntity().getRealAmount()));
									edit.setDelFlag("0");
									haveReceiveRefundServiceFacade.updateByPrimaryKey(edit, true);
								}

							}
						}

						Long receivablesId = hrResponse.getEntity().getReceivablesId();
						// 未收金额
						Response<NeedReceiveRefund> nrResponse = needReceiveRefundServiceFacade.findById(receivablesId);
						// 已收金额
						Response<BigDecimal> hraResponse = haveReceiveRefundServiceFacade.findHaveAmount(receivablesId);
						if (checkedFlag.equals("2")) {
							if (nrResponse.isSuccess()
									&& hraResponse.isSuccess()
									&& nrResponse.getEntity().getTotalReceivablesAmount()
											.compareTo(hraResponse.getEntity()) > 0) {
								// 更新应收款记录为未删除
								NeedReceiveRefundDto edit = new NeedReceiveRefundDto();
								edit.setId(nrResponse.getEntity().getId());
								edit.setDelFlag("0");
								edit.setStatus("1");
								needReceiveRefundServiceFacade.updateByPrimaryKey(edit, true);
							}
						}
						// 查询应收款的已收款记录,处理按揭复核状态
						if (checkedFlag.equals("1")) {
							HaveReceiveRefundDto queryHRRD = new HaveReceiveRefundDto();
							queryHRRD.setReceivablesId(hrResponse.getEntity().getReceivablesId());
							ResponseList<HaveReceiveRefund> hrrListResponse = haveReceiveRefundServiceFacade
									.findByDto(queryHRRD);
							if (hrrListResponse.isSuccess() && null != hrrListResponse.getEntity()) {
								int totalCheckCount = hrrListResponse.getEntity().size();
								// 复核通过次数
								int checkPassCount = 0;
								// 复核未通过次数
								int checkNoPassCount = 0;
								for (HaveReceiveRefund hrr : hrrListResponse.getEntity()) {
									// 0 未复核 1 已复核
									String reCheck = hrr.getReChecked();
									if (reCheck.equals("0")) {
										checkNoPassCount++;
									} else if (reCheck.equals("1")) {
										checkPassCount++;
									}
								}
								// 资金复核状态 0未复核 1复核通过 2复核未通过
								String mortgageCheckStatus = "0";
								if (checkPassCount == totalCheckCount) {
									// 复核通过
									mortgageCheckStatus = "1";
								} else if (checkNoPassCount > 0) {
									// 复核未通过
									mortgageCheckStatus = "2";
								}
								MortgageRecordDto entity = new MortgageRecordDto();
								entity.setNeedId(nrResponse.getEntity().getId());
								ResponseList<MortgageRecord> rlMrList = mortgageRecordServiceFacade.findByDto(entity);
								if (rlMrList.isSuccess() && null != rlMrList.getEntity()
										&& rlMrList.getEntity().size() > 0) {
									List<MortgageRecord> mortgageRecords = rlMrList.getEntity();
									for (MortgageRecord mortgageRecord : mortgageRecords) {
										MortgageRecordDto updateDto = new MortgageRecordDto();
										updateDto.setId(mortgageRecord.getId());
										updateDto.setMortgageCheckStatus(mortgageCheckStatus);
										mortgageRecordServiceFacade.updateByPrimaryKey(updateDto, true);
									}
								}
							}
						} else if (checkedFlag.equals("2")) {
							// 更新按揭收款状态
							if (nrResponse.isSuccess() && hraResponse.isSuccess()) {
								// 查询应收款对应的按揭记录
								MortgageRecordDto entity = new MortgageRecordDto();
								entity.setNeedId(nrResponse.getEntity().getId());
								ResponseList<MortgageRecord> rlMrList = mortgageRecordServiceFacade.findByDto(entity);
								// 当存在按揭记录才去更新
								if (rlMrList.isSuccess() && null != rlMrList.getEntity()
										&& rlMrList.getEntity().size() > 0) {
									List<MortgageRecord> mortgageRecords = rlMrList.getEntity();
									// 应收金额
									BigDecimal totalReceivablesAmount = nrResponse.getEntity()
											.getTotalReceivablesAmount();
									// 已收金额
									BigDecimal haveAmount = hraResponse.getEntity();

									if (haveAmount.compareTo(BigDecimal.ZERO) <= 0) {
										// 当已收款金额小于等于0时更新按揭收款状态为未收款
										for (MortgageRecord mortgageRecord : mortgageRecords) {
											MortgageRecordDto updateDto = new MortgageRecordDto();
											updateDto.setId(mortgageRecord.getId());
											updateDto.setMortgageReceivedStatus("0");// 已收款
											mortgageRecordServiceFacade.updateByPrimaryKey(updateDto, true);
										}
									} else if (haveAmount.compareTo(BigDecimal.ZERO) > 0
											&& haveAmount.compareTo(totalReceivablesAmount) < 0) {
										// 当已收款金额大于0而且小于应收款金额时更新按揭收款状态为部分付款
										for (MortgageRecord mortgageRecord : mortgageRecords) {
											MortgageRecordDto updateDto = new MortgageRecordDto();
											updateDto.setId(mortgageRecord.getId());
											updateDto.setMortgageReceivedStatus("1");// 已收款
											mortgageRecordServiceFacade.updateByPrimaryKey(updateDto, true);
										}
									} else if (haveAmount.compareTo(totalReceivablesAmount) >= 0) {
										// 当已收款金额大于等于应收款金额时更新按揭收款状态为已付款
										for (MortgageRecord mortgageRecord : mortgageRecords) {
											MortgageRecordDto updateDto = new MortgageRecordDto();
											updateDto.setId(mortgageRecord.getId());
											updateDto.setMortgageReceivedStatus("2");// 已收款
											mortgageRecordServiceFacade.updateByPrimaryKey(updateDto, true);
										}
									}

								}
							}
						}

					}
				}

				return response.isSuccess();
			} catch (Exception e) {
				logger.error(e.toString(), e);
			}
		}
		return false;
	}

	// 删除
	@RequestMapping(value = "delete", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes delete(Long id) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用查看接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "marketing:haveReceiveRefund:delete"))) {
			try {
				Response<Integer> response = haveReceiveRefundServiceFacade.deleteByPrimaryKey(id);
				if (response.isSuccess()) {
					ar.setSucceedMsg(Const.DEL_SUCCEED);
				} else {
					ar.setFailMsg(Const.DEL_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.DEL_FAIL);
			}
		}
		return ar;
	}
	/**
	 * 
	 * haveReceicerefundExport:(已收款导出). <br/>
	 * @author Administrator
	 * @param request
	 * @param json
	 * @param response
	 * @since JDK 1.6
	 */
	@RequestMapping(value = "haveReceicerefundExport")
	public void haveReceicerefundExport(HttpServletRequest request, String json,HttpServletResponse response) throws Exception{
		AjaxRes ar = getAjaxRes();
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"fin:haveReceive:list"))) {
			String[] name = null;
			List<String[]> headerList = new ArrayList<String[]>(); 
			List<List<Map<String, String>>> list = new ArrayList<List<Map<String, String>>>(); //数据集合
			String[] header = new String[]{
					"客户名称","房号","签约面积(㎡)","签约单价(元)","签约金额(元)","房款类型","业务标志","发生额","票据号码","结算日期/结算人员/结算方式","结算银行","备注","复核状态","操作日期"
			};
			String jsonStr=URLDecoder.decode(json,"utf-8");
			HaveReceiveRefundInfoDto dto = JSONObject.parseObject(jsonStr, HaveReceiveRefundInfoDto.class);
			if(dto.getDocType().equals(DocTypeEnum.COLLECTION.getNo())){
				name = new String[]{"已收款明细"};
			}else{
				name = new String[]{"已退款明细"};
			}
			headerList.add(header);
			dto = setQueryHaveReceive(dto);
			dto.setIsExport("1");
			Page<HaveReceiveRefundInfo> responseList = haveReceiveRefundServiceFacade.findPageByDtoInfo(dto,PageUtil.begin(0, 10), 10);
			List<Map<String, String>> listMap = needReceicerefundExportService.returnFieldHaveReceiveRefund(responseList.getRows(), header);
			list.add(listMap);
			ExcelUtil.exportExcel(list, headerList, name, response);
		}
	}
	
	// 分页查询
	@RequestMapping(value = "list")
	@ResponseBody
	public Page<HaveReceiveRefundInfo> list(HttpServletRequest request, HaveReceiveRefundInfoDto dto, Integer page, Integer limit) {
		/*
		 * 1.判断权限2.调用分页查询接口3.返回信息
		 */
		String authStr = "fin:haveReceive:list";
		if (doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, authStr/*"fin:needReceive:checkList" 此权限为复核查询功能*/)) {
			try {
				dto.setYsDateStart(request.getParameter("ysDateStart"));
				dto.setYsDateEnd(request.getParameter("ysDateEnd"));
				dto = setQueryHaveReceive(dto);
				Page<HaveReceiveRefundInfo> response = haveReceiveRefundServiceFacade.findPageByDtoInfo(dto,PageUtil.begin(page, limit), limit);
				if (response.getSuccess()) {
					if (null == response.getRows()) {
						response.setRows(new ArrayList<HaveReceiveRefundInfo>());
					}
					response.setPageNumber(page);
					return response;
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
			}
		}
		return new Page<HaveReceiveRefundInfo>();
	}

	public HaveReceiveRefundInfoDto setQueryHaveReceive(HaveReceiveRefundInfoDto dto) throws Exception{
		User user = ShiroUtil.getCurrentUser();
		dto.setMerchantId(user.getMerchantId());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String ysDateStart = dto.getYsDateStart();
		if (StringUtils.isNotBlank(ysDateStart)) {
			ysDateStart += " 00:00:00";
			dto.setStatementDateBefore(sdf.parse(ysDateStart));
		}
		String ysDateEnd = dto.getYsDateEnd();
		if (StringUtils.isNotBlank(ysDateEnd)) {
			ysDateEnd += " 23:59:59";
			dto.setStatementDateAfter(sdf.parse(ysDateEnd));
		}
		dto.setDelFlag("0"); // 未删除
		dto.setPermissionUserId(user.getId());
		dto.setOrders(" t.create_time desc ");
		dto.setPermissionUserId(user.getId());
		return dto;
	}
	
	// 分页查询
	@RequestMapping(value = "re_checked_list")
	@ResponseBody
	public Page<HaveReceiveRefundInfo> re_checked_list(HaveReceiveRefundInfoDto dto, Integer page, Integer limit,
			String jsDateEnd, String jsDateStart, String needAuth) {
		/*
		 * 1.判断权限2.调用分页查询接口3.返回信息
		 */
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		boolean authFlag = doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "fin:needReceive:checkList");
		if(null != needAuth && "F".equals(needAuth)){
			authFlag = true;
		}
		if (authFlag) {
			try {
				if (!com.alibaba.druid.util.StringUtils.isEmpty(jsDateEnd)) {
					dto.setStatementDateAfter(df.parse(jsDateEnd + " 23:59:59"));
				}

				if (!com.alibaba.druid.util.StringUtils.isEmpty(jsDateStart)) {
					dto.setStatementDateBefore(df.parse(jsDateStart + " 00:00:00"));
				}
				User user = ShiroUtil.getCurrentUser();
				dto.setMerchantId(user.getMerchantId());
				dto.setDelFlag("0"); // 未删除
				dto.setPermissionUserId(user.getId());
				Page<HaveReceiveRefundInfo> response = haveReceiveRefundServiceFacade.findPageByDtoInfo(dto,
						PageUtil.begin(page, limit), limit);
				if (response.getSuccess()) {
					if (null == response.getRows()) {
						response.setRows(new ArrayList<HaveReceiveRefundInfo>());
					} else {
						List<HaveReceiveRefundInfo> list = response.getRows();
						for (int i = 0; i < list.size(); i++) {
							HaveReceiveRefundInfo info = (HaveReceiveRefundInfo) list.get(i);
							if (info.getReceivablesType().equals(BusinessTypeEnum.SIGNED.getNo())) {
								// 查询签约信息
								Response<Signed> resp = signedServiceFacade.findById(info.getRelationId());
								if (resp.isSuccess() && resp.getEntity() != null) {
									info.setCalculatArea(resp.getEntity().getCalculateArea().toString());
									info.setPrice(resp.getEntity().getSignPrice());
									info.setTotalPrice(resp.getEntity().getSignAmount());
								}
							} else if (info.getReceivablesType().equals(BusinessTypeEnum.AREA.getNo())) {
								// 面积补差
								Response<ReserveArea> res = reserveAreaServiceFacade.findById(info.getRelationId());
								if (res.isSuccess() && res.getEntity() != null) {
									// 签约信息
									Response<Signed> resp = signedServiceFacade.findById(res.getEntity().getSignedId());
									if (resp.isSuccess() && resp.getEntity() != null) {
										info.setSignId(resp.getEntity().getId());
										info.setCalculatArea(resp.getEntity().getCalculateArea().toString());
										info.setPrice(resp.getEntity().getSignPrice());
										info.setTotalPrice(resp.getEntity().getSignAmount());
									}
								}
							}
							if (StringUtils.isNotBlank(info.getHousingFundType())) {
								// 房款类型
								info.setRelationType(HousingFundTypeEnum.getByNo(info.getHousingFundType()).getDes());
							}
							if (StringUtils.isNotBlank(info.getBusinessFlag())) {
								// 业务标志
								info.setBusinessType(BusinessFlagEnum.getByNo(info.getBusinessFlag()).getDes());
							}
							// 结算日期 + 结算人员 + 结算方式
							String statement = "";
							if (info.getStatementDate() != null) {
								SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
								statement = sdf.format(info.getStatementDate());
							}
							if (StringUtils.isNotBlank(info.getStatement_name())) {
								statement = statement + "/" + info.getStatement_name();
							}
							if (info.getStatementType() != null) {
								info.setPaymentMethod_name(StatementTypeEnum.getByNo(info.getStatementType() + "")
										.getDes());
								statement = statement + "/"
										+ StatementTypeEnum.getByNo(info.getStatementType() + "").getDes();
							}
							info.setStatement(statement);
							if (info.getCheckUserId() != null) {
								Response<User> res = userServiceFacade.findById(info.getCheckUserId());
								info.setChecked_name(res.getEntity().getUserName());
							}

							// 票据信息，当新票据号不为空时取新票据号
							if (StringUtils.isNotBlank(info.getNewBillCode())) {
								info.setBillCode(info.getNewBillCode());
							}
						}
					}
					response.setPageNumber(page);
					return response;
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
			}
		}
		return new Page<HaveReceiveRefundInfo>();
	}

	// 退款页面列表
	@RequestMapping(value = "refund_list_view")
	@ResponseBody
	public Page<HaveReceiveRefundInfo> refund_list_view(HttpServletRequest request, long id, Integer page, Integer limit) {
		/*
		 * 1.判断权限2.调用分页查询接口3.返回信息
		 */
		if (doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "fin:haveReceive:refund")) {
			try {
				String needOrHave = request.getParameter("needOrHave");
				if ("have".equals(needOrHave)) {
					HaveReceiveRefundInfoDto dto = new HaveReceiveRefundInfoDto();
					dto.setDelFlag("0"); // 未删除
					dto.setId(id);
					Page<HaveReceiveRefundInfo> have = haveReceiveRefundServiceFacade.findPageByDtoInfo(dto,
							PageUtil.begin(page, limit), limit);
					if (have.getSuccess() && null != have.getRows()) {
						List<HaveReceiveRefundInfo> list = have.getRows();
						for (int i = 0; i < list.size(); i++) {
							HaveReceiveRefundInfo info = (HaveReceiveRefundInfo) list.get(i);
							// 房款类型
							if (StringUtils.isNotBlank(info.getHousingFundType())) {
								info.setRelationType(HousingFundTypeEnum.getByNo(info.getHousingFundType()).getDes());
							}
							// 业务标志
							if (StringUtils.isNotBlank(info.getBusinessFlag())) {
								info.setBusinessType(BusinessFlagEnum.getByNo(info.getBusinessFlag()).getDes());
							}
							// 票据信息，当新票据号不为空时取新票据号
							if (StringUtils.isNotBlank(info.getNewBillCode())) {
								info.setBillCode(info.getNewBillCode());
							}
							// 结算方式
							if (StringUtils.isNotBlank(info.getPaymentMethod())) {
								info.setPaymentMethod_name(PaymentMethodEnum.getByNo(info.getPaymentMethod()).getDes());
							}
						}
					} else {
						have.setRows(new ArrayList<HaveReceiveRefundInfo>());
					}
					have.setPageNumber(page);
					return have;
				} else {
					Page<HaveReceiveRefundInfo> pageModel = new Page<HaveReceiveRefundInfo>();
					List<HaveReceiveRefundInfo> listModel = new ArrayList<HaveReceiveRefundInfo>();
					NeedReceiveRefundInfoDto dto = new NeedReceiveRefundInfoDto();
					dto.setDelFlag("0"); // 未删除
					dto.setId(id);
					Page<NeedReceiveRefundInfo> need = needReceiveRefundServiceFacade.findPageByDtoInfo(dto,
							PageUtil.begin(page, limit), limit);
					if (need.getSuccess() && need.getRows() != null) {
						List<NeedReceiveRefundInfo> list = need.getRows();
						for (int i = 0; i < list.size(); i++) {
							NeedReceiveRefundInfo info = (NeedReceiveRefundInfo) list.get(i);

							HaveReceiveRefundInfo entity = new HaveReceiveRefundInfo();
							BeanUtils.copyProperties(info, entity);
							entity.setReceivablesType(info.getBusinessType()); // 业务类型
							entity.setReceivablesId(info.getRelationId()); // 业务ID
							// 房款类型
							if (StringUtils.isNotBlank(info.getHousingFundType())) {
								entity.setRelationType(HousingFundTypeEnum.getByNo(info.getHousingFundType()).getDes());
							}
							// 业务标志
							if (StringUtils.isNotBlank(info.getBusinessFlag())) {
								entity.setBusinessType(BusinessFlagEnum.getByNo(info.getBusinessFlag()).getDes());
							}
							entity.setRealAmount(info.getTotalReceivablesAmount());
							listModel.add(entity);
						}

					}
					pageModel.setRows(listModel);
					pageModel.setTotal(need.getTotal());
					pageModel.setTotalPages(need.getTotalPages());
					pageModel.setPageNumber(page);
					return pageModel;
				}

			} catch (Exception e) {
				logger.error(e.toString(), e);
			}
		}
		return new Page<HaveReceiveRefundInfo>();
	}

	// 查询公司员工
	@RequestMapping(value = "findUserByMerID")
	@ResponseBody
	public List<User> findUserByDeptId(String type) {
		try {
			Long roleId = null;
			if (!com.alibaba.druid.util.StringUtils.isEmpty(type)) {
				RoleDto roleDto = new RoleDto();
				roleDto.setRoleName("经纪人");
				Role role = roleServiceFacade.findByDto(roleDto).getEntity().get(0);
				roleId = role.getId();
			}
			User user = ShiroUtil.getCurrentUser();
			UserDto dto = new UserDto();
			dto.setMerchantId(user.getMerchantId());
			dto.setRoleId(roleId);
			dto.setUserStatus("0");
			dto.setIsAdmin("0");
			ResponseList<User> responseList = userServiceFacade.findByDto(dto);
			if (responseList.isSuccess() && null != responseList.getEntity()) {
				return responseList.getEntity();
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return new ArrayList<User>();
	}

	// 查询公司客户
	@RequestMapping(value = "findCustomer")
	@ResponseBody
	public List<Customer> findCustomer() {
		try {
			User user = ShiroUtil.getCurrentUser();
			CustomerDto dto = new CustomerDto();
			dto.setMerchantId(user.getMerchantId());
			ResponseList<Customer> responseList = customerServiceFacade.findByDto(dto);
			if (responseList.isSuccess() && null != responseList.getEntity()) {
				return responseList.getEntity();
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return new ArrayList<Customer>();
	}

	// 查询房间list
	@RequestMapping(value = "findRoomId")
	@ResponseBody
	public List<ProjectRoom> findRoomId() {
		try {
			User user = ShiroUtil.getCurrentUser();
			ProjectRoomDto dto = new ProjectRoomDto();
			dto.setMerchantId(user.getMerchantId());
			ResponseList<ProjectRoom> responseList = projectRoomServiceFacade.findByDto(dto);
			if (responseList.isSuccess() && null != responseList.getEntity()) {
				return responseList.getEntity();
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return new ArrayList<ProjectRoom>();
	}

	// 结算方式枚举
	@RequestMapping(value = "statementTypeEnum")
	@ResponseBody
	public List<value> statementTypeEnum() {
		List<value> list = new ArrayList<value>();
		try {
			HaveReceiveRefundController h = new HaveReceiveRefundController();
			StatementTypeEnum[] types = StatementTypeEnum.values();
			for (int i = 0; i < types.length; i++) {
				value type = h.new value();
				type.setId(types[i].getNo());
				type.setValue(types[i].getDes());
				list.add(type);
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return list;
	}

	// 业务类型枚举
	@RequestMapping(value = "businessFlagEnum")
	@ResponseBody
	public List<value> businessFlagEnum() {
		List<value> list = new ArrayList<value>();
		try {
			User user = ShiroUtil.getCurrentUser();
			// 认筹开关,默认未关闭(false) ,true已关闭
			boolean payDepositOff = false;
			Response<Boolean> response = merchantServiceFacade.merPayDepositOff(user.getMerchantId());
			if (response.isSuccess()) {
				payDepositOff = response.getEntity();
			}
			HaveReceiveRefundController h = new HaveReceiveRefundController();
			BusinessFlagEnum[] types = BusinessFlagEnum.values();
			for (int i = 0; i < types.length; i++) {
				if (payDepositOff && types[i].getDes().contains("认筹")) {
					continue;
				}
				value type = h.new value();
				type.setId(types[i].getNo());
				type.setValue(types[i].getDes());
				list.add(type);
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return list;
	}

	class value {
		private String id;
		private String value;

		public String getId() {
			return id;
		}

		public void setId(String id) {
			this.id = id;
		}

		public String getValue() {
			return value;
		}

		public void setValue(String value) {
			this.value = value;
		}
	}

	public static void main(String[] args) {
		double i = Math.pow(2, 240);
		System.out.println(new BigDecimal(i));
	}
}
